package com.spring.demo.untils.document.handle;

import com.spring.demo.untils.document.ClassUtils;
import com.spring.demo.untils.document.annotions.Mapper;
import com.spring.demo.untils.document.annotions.Mapping;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Objects;

/**
 * @author xuweizhi
 * @since 2023/04/26 10:34
 */
public class MapMapping1 implements OutputHandle<Void> {


    public void test(String line, Integer index, Class<?> clazz, Map<Integer, String> indexMapping) {
        if (ClassUtils.isPrimitiveOrWrapper(clazz) || Objects.equals(String.class, clazz)) {
            return;
        }

        String[] split = line.split("\t");
        try {
            Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            Object instance = declaredConstructor.newInstance();

            if (indexMapping != null) {
                // 按照字段映射赋值
                for (Map.Entry<Integer, String> entry : indexMapping.entrySet()) {
                    Field declaredField = clazz.getDeclaredField(entry.getValue());
                    declaredField.setAccessible(true);
                    declaredField.set(instance, split[index]);
                }
            } else if (clazz.isAnnotationPresent(Mapper.class)) {
                Field[] declaredFields = clazz.getDeclaredFields();
                // 按照注解赋值
                for (Field declaredField : declaredFields) {
                    if (declaredField.isAnnotationPresent(Mapping.class)) {
                        declaredField.setAccessible(true);
                        Mapping mapping = declaredField.getAnnotation(Mapping.class);
                        if (mapping != null) {
                            declaredField.set(instance, split[mapping.index()]);
                        }
                    }
                }
            } else {
                // for (String value : split) {
                //     // 按照分割符赋值
                //     if (value.contains(":")) {
                //         String[] filedValue = value.split(":");
                //         Field declaredField = clazz.getDeclaredField(filedValue[0]);
                //         if (declaredField != null) {
                //             declaredField.setAccessible(true);
                //             declaredField.set(instance, filedValue[1]);
                //
                //         }
                //     }
                // }
            }
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException |
                 NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public Void handle(String line) {
        return null;
    }
}
